package com.dupf.product.web.jms;

import com.dupf.product.dao.model.ProductVariant;
import com.dupf.product.dao.model.ProductVariantExample;
import com.dupf.product.rpc.api.ProductVariantService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.jms.*;

/**
 * MQ消费者
 * Created by dupf on 2018/3/15.
 */
public class DefaultMessageQueueListener implements MessageListener {

    private static final Logger LOGGER = LoggerFactory.getLogger(DefaultMessageQueueListener.class);

    @Autowired
    ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Autowired
    private ProductVariantService productVariantService;

    @Override
    public void onMessage(final Message message) {
        // 使用线程池多线程处理
        threadPoolTaskExecutor.execute(new Runnable() {
            @Override
            public void run() {

                if (message instanceof TextMessage) {
                    TextMessage textMessage = (TextMessage) message;
                    try {

                        JSONObject data = JSONObject.fromObject(textMessage.getText());

                        if (StringUtils.isNotEmpty(data.optString("variant"))) {
                            // [{"variant":"color","args":["A","B","C"]},{"variant":"size","args":["7X"]}]
                            JSONArray variantArr = JSONArray.fromObject(data.optString("variant"));
                            if (variantArr != null && variantArr.size() > 0) {
                                for (Object o : variantArr) {
                                    JSONObject item = JSONObject.fromObject(o.toString());
                                    Integer type = 1;
                                    if (item.optString("variant").equals("size")) {
                                        type = 2;
                                    }

                                    String args = item.optString("args");
                                    if (StringUtils.isNotEmpty(args)) {

                                        JSONArray argsJson = JSONArray.fromObject(args);

                                        for (Object arg : argsJson) {

                                            ProductVariantExample example = new ProductVariantExample();
                                            example.createCriteria().andUserIdEqualTo(data.getInt("userId"))
                                                    .andTypeEqualTo(type).andVariantZhEqualTo(arg.toString());

                                            long count = productVariantService.countByExample(example);

                                            if (count <= 0) {
                                                try {
                                                    ProductVariant insertProductVar = new ProductVariant();
                                                    insertProductVar.setOrgId(data.getInt("orgId"));
                                                    insertProductVar.setUserId(data.getInt("userId"));
                                                    insertProductVar.setType(type);
                                                    insertProductVar.setVariantZh(arg.toString());
                                                    insertProductVar.setCtime(System.currentTimeMillis());
                                                    insertProductVar.setOrders(1);
                                                    productVariantService.insertSelective(insertProductVar);
                                                } catch (Exception e) {
                                                    LOGGER.warn("改变体已存在: " + arg);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else if (message instanceof ObjectMessage) {
                    try {
                        ((ObjectMessage) message).getObject();
                    } catch (JMSException e) {
                        e.printStackTrace();
                    }

                }

            }
        });
    }

}
